import React, { useState, useRef, useEffect } from 'react';
import {
  Dialog,
  TextArea,
  Space,
  Avatar,
  NavBar
} from 'antd-mobile';
import { DeleteOutline } from 'antd-mobile-icons'
import { SendOutlined } from '@ant-design/icons';
import styles from './index.module.less';
import { Bubble, Sender } from '@ant-design/x';
const { getTickets, sendTicketMessage, deleteAllTicketMessage } = $globalServicer('My')
const ServiceChat = () => {
  const [value, setValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [messages, setMessages] = useState([]);
  const listRef = useRef(null);
  const AiAvatar = useRef(null);
  const UserAvatar = useRef(null);
  const [roles, setRoles] = useState({
    ai: {
      placement: 'start',
      avatar: { icon: <Avatar src={AiAvatar.current} /> },
      // avatar: { icon: AiAvatar.current },
      style: {
        maxWidth: 600,
        marginInlineEnd: 44,
      },
    },
    user: {
      placement: 'end',
      avatar: { icon: <Avatar src={UserAvatar.current} /> },
      // avatar: { icon: UserAvatar.current },
      style: {
        maxWidth: 600,
      },
    },
  });
  const customNavigate = $globalNavigate()
  // 添加滚动到底部的方法
  const scrollToBottom = () => {
    if (listRef.current) {
      const element = listRef.current;
      element.scrollTop = element.scrollHeight;
    }
  };
  useEffect(() => {
    scrollToBottom();
  }, [messages]);
  useEffect(() => {
    getTickets().then(res => {
      // 这里需要拿到消息中的两个角色，来填充role 中的 avatar
      // 获取 AI 和用户头像
      if (res.length) {
        const aiAvatar = res.find(item => item.type === 1)?.cover;
        const userAvatar = res.find(item => item.type !== 1)?.cover;
        setRoles({
          ai: {
            placement: 'start',
            avatar: { icon: <Avatar src={aiAvatar} /> },
            style: {
              maxWidth: 600,
              marginInlineEnd: 44,
            },
          },
          user: {
            placement: 'end',
            avatar: { icon: <Avatar src={userAvatar} /> },
            style: {
              maxWidth: 600,
            },
          },
        })
        setMessages(res)
      }
    })
  }, [])

  const sendMessage = async (msg) => {
    sendTicketMessage({
      message: msg
    }).then(res => {
    })
    setMessages([...messages, { id: Date.now(), type: 0, message: msg, timestamp: Date.now() }]);
  };
  const handleDeleteAll = async () => {
    Dialog.confirm({
      title: '结束本次对话',
      content: '确定要结束本次对话吗？',
    }).then(async (result) => {
      if (result) {
        await deleteAllTicketMessage()
        setMessages([])
      }
    })
  }
  const renderSend = (
    props = {
      ignoreLoading: false,
      placeholder: '发消息，AI生成回复',
      btnProps: {
        color: 'primary',
        shape: 'default',
      }
    },
  ) => {
    const { ignoreLoading, placeholder, ...btnProps } = props;

    return (
      <Sender
        value={value}
        onChange={setValue}
        loading={loading}
        onSubmit={async (msg) => {
          if (!msg.trim()) return;
          setLoading(true);
          await sendMessage(msg);
          setValue('');
          setLoading(false);
        }}
        placeholder={placeholder}
        onCancel={() => {
          setLoading(false);
        }}
        actions={(_, info) => {
          const { SendButton, LoadingButton } = info.components;
          if (!ignoreLoading && loading) {
            return (
              <LoadingButton />
            );
          }

          let node = <SendButton {...btnProps} />;

          if (!ignoreLoading) {
            node = (
              <>{node}</>
            );
          }
          return node;
        }}
      />
    );
  };
  const right = (
    <div style={{ fontSize: 24 }} onClick={handleDeleteAll}>
      <Space style={{ '--gap': '16px' }}>
        <DeleteOutline />
      </Space>
    </div>
  )
  useEffect(() => {
    // 监听视口大小变化（键盘弹出/收起）
    const handleResize = () => {
      // 延迟执行滚动，确保键盘完全弹出
      setTimeout(scrollToBottom, 100);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return (
    <div className={styles.warp}>
      <div className={styles.header}>
        <NavBar
          onBack={() => {
            customNavigate('/my')
          }}
          right={right}
        >
          客服消息
        </NavBar>
      </div>
      <div className={styles.chat_container}>
        <Bubble.List
          ref={listRef}
          roles={roles}
          autoScroll={true}
          className={styles.message_list}
          items={messages.map((_, i) => {
            return {
              key: i,
              role: _.type === 1 ? 'ai' : 'user',
              content: _.message,
              loading: _.loading,
            };
          })}
        />
      </div>
      <div className={styles.button_wrapper}>
        {renderSend({
          variant: 'text',
          placeholder: '发消息，客服会尽快回复',
          color: 'primary',
          icon: <SendOutlined />,
          shape: 'default',
        })}
      </div>
    </div>
  );
};

export default ServiceChat;
